package music_store.ms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import music_store.ms.common.Const;
import music_store.ms.common.ResponseCode;
import music_store.ms.common.ServerResponse;
import music_store.ms.dao.CartMapper;
import music_store.ms.dao.MusicMapper;
import music_store.ms.dao.OrderItemMapper;
import music_store.ms.dao.OrderMapper;
import music_store.ms.pojo.Cart;
import music_store.ms.pojo.Music;
import music_store.ms.pojo.Order;
import music_store.ms.pojo.OrderItem;
import music_store.ms.service.IOrderService;
import music_store.ms.util.BigDecimalUtil;
import music_store.ms.vo.MusicSalesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

@Service("iOrderService")
public class OrderServiceImpl implements IOrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    MusicMapper musicMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    //portal

    public ServerResponse<Order> createOrder (Integer userId){
        //找到userId对应的购物车list
        List<Cart> cartList = cartMapper.selectCheckedCartByUserId(userId);
        ServerResponse response = assembleOrderItem(userId,cartList);
        if (!response.isSuccess()){
            return response;
        }
        List<OrderItem> orderItemList= (List<OrderItem>) response.getData();
        BigDecimal payment = this.getOrderTotalPrice(orderItemList);

        Order order = this.assembleOrder(userId,payment);

        if (order == null){
            return ServerResponse.createByErrorMessage("生成订单错误。");
        }

        if (CollectionUtils.isEmpty(orderItemList)){
            return ServerResponse.createByErrorMessage("购物车为空。");
        }
        for (OrderItem orderItem : orderItemList){
            //assembleOrderItem没有setOrderNo，而是在此set。
            orderItem.setOrderNo(order.getOrderNo());
        }
        //批量插入orderItem到数据库
        for (OrderItem orderItem : orderItemList){
            orderItemMapper.insert(orderItem);
        }

        //生成成功，情空购物车。
        this.cleanCart(cartList);

        //没时间做vo，直接返回order =,=
        return ServerResponse.createBySuccess(order);
    }

    public ServerResponse<PageInfo> getList (Integer userId, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Order> orderList = orderMapper.selectByUserId(userId);
        if (orderList == null){
            return ServerResponse.createByErrorMessage("该用户还没有订单。");
        }

        PageInfo pageInfo = new PageInfo(orderList);
        pageInfo.setList(orderList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    public ServerResponse<PageInfo> getOrderDetail (Long orderNo, Integer pageNum, Integer pageSize){
        if (orderNo == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<OrderItem> orderItemList = orderItemMapper.selectByOrderNo(orderNo);
        if (orderItemList == null){
            return ServerResponse.createByErrorMessage("订单内无详情。");
        }

        PageInfo pageInfo = new PageInfo(orderItemList);
        pageInfo.setList(orderItemList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    //backend

    public ServerResponse checkSales(Integer pageNum, Integer pageSize){
        List<MusicSalesVo> musicSalesVoList = orderItemMapper.checkSales();

        PageHelper.startPage(pageNum,pageSize);
        PageInfo pageInfo = new PageInfo(musicSalesVoList);
        pageInfo.setList(musicSalesVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }




    //私有方法

    //由cart类组装成orderitem类的一个方法
    private ServerResponse<List<OrderItem>> assembleOrderItem(Integer userId, List<Cart> cartList){
        List<OrderItem> orderItemList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(cartList)){
            return ServerResponse.createByErrorMessage("购物车为空。");
        }

        for (Cart cartItem : cartList){
            OrderItem orderItem = new OrderItem();

            //检测选中的单曲是否为售卖状态。
            Music music = musicMapper.selectByPrimaryKey(cartItem.getMusicId());
            if (music == null){
                return ServerResponse.createByErrorMessage("找不到单曲。");
            }

            if (Const.ProductStatusEnum.ON_SALE.getCode() != music.getStatus()  ){
                return ServerResponse.createByErrorMessage("单曲"+music.getName()+"不是售卖状态。");
            }

            //组装orderItem
            orderItem.setUserId(userId);
            orderItem.setMusicId(music.getId());
            orderItem.setMusicName(music.getName());
            orderItem.setCurrentUnitPrice(music.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalPrice(BigDecimalUtil.mul(music.getPrice().doubleValue(),orderItem.getQuantity()));

            orderItemList.add(orderItem);
        }
        return ServerResponse.createBySuccess(orderItemList);
    }

    //获取订单总价。
    private BigDecimal getOrderTotalPrice(List<OrderItem> orderItemList){
        BigDecimal payment = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList){
            payment = BigDecimalUtil.add(payment.doubleValue(),orderItem.getTotalPrice().doubleValue());
        }
        return payment;
    }

    //组装Order的一个方法。
    private Order assembleOrder(Integer userId,BigDecimal payment){
        Order order = new Order();
        order.setOrderNo(this.generateOrderNo());
        order.setUserId(userId);
        order.setPayment(payment);
        order.setPaymentType(Const.PaymentTypeEnum.ONLINE_PAY.getCode());
        order.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());

        int rowCount = orderMapper.insert(order);
        if (rowCount > 0){
            return order;
        }
        return null;
    }

    //生成无序的orderNo的一个方法
    private long generateOrderNo(){
        long currentTime = System.currentTimeMillis();
        return currentTime+new Random().nextInt(100 );
    }

    //清空购物车
    private void cleanCart(List<Cart> cartList){
        for (Cart cart:cartList ){
            cartMapper.deleteByPrimaryKey(cart.getId());
        }
    }



}
